package dimension.starry.block.machine.simple.smelter;

import dimension.starry.StarryDimension;
import dimension.starry.block.machine.simple.SimpleMachineRegister;
import dimension.starry.block.typeInterface.MachineTileEntity;
import dimension.starry.item.ItemRegisterManager;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

/**
 * @author 150149
 */
public class SmelterTileEntity extends MachineTileEntity {

    private static final Text TITLE = Text.translatable("block." + StarryDimension.MOD_ID + ".smelter");

    public SmelterTileEntity(BlockPos blockPos, BlockState blockState) {
        super(SimpleMachineRegister.SMELTER.getBlockEntityType(), blockPos, blockState, 4, TITLE, 800);
    }

    @Override
    public ScreenHandler createMenu(int sycID, PlayerInventory inventory, PlayerEntity player) {
        return new SmelterContainer(SimpleMachineRegister.SMELTER.getScreenHandlerType(), sycID, inventory, getPos());
    }

    @Override
    public void tick(World world, BlockPos pos, BlockState blockState, MachineTileEntity blockEntity) {
        if (world == null || world.isClient()) {
            return;
        }
        ItemStack copperItemStack = this.inventory.getStack(0);
        ItemStack tinItemStack = this.inventory.getStack(1);
        ItemStack fuelItemStack = this.inventory.getStack(2);

        if (copperItemStack.isEmpty() || tinItemStack.isEmpty()) {
            this.setMachineStatus(false);
            this.resetProgress();
        } else if (!copperItemStack.getItem().equals(Items.COPPER_INGOT) &&
            !tinItemStack.getItem().equals(ItemRegisterManager.TIN.getItem())) {
            this.setMachineStatus(false);
            this.resetProgress();
        } else if (this.getProgress() >= this.getConsumeTime()) {
            ItemStack itemStack = new ItemStack(ItemRegisterManager.BRONZE.getItem());
            if (this.inventory.canInsert(itemStack)) {
                copperItemStack.setCount(copperItemStack.getCount() - 1);
                tinItemStack.setCount(tinItemStack.getCount() - 1);
                this.inventory.addStack(itemStack);
                this.resetProgress();
            }
        } else if (!this.consumeFuel() && !fuelItemStack.isEmpty() && getFuelAddCount(fuelItemStack.getItem()) != 0) {
            fuelItemStack.setCount(fuelItemStack.getCount() - 1);
            this.addFuel(getFuelAddCount(fuelItemStack.getItem()));
            this.consumeFuel();
            this.setMachineStatus(true);
        }
    }

}
